package org.locker.netty.dto;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import org.locker.common.core.utils.StringUtils;

import static org.locker.netty.NettySocketServer.delimiterCode;

/**
 * @author: winnie
 * @create: 2023-10-04
 * @Description:
 */
@Getter
@Setter
@Builder
public class MessageObject {

    private MessageEnum code;

    private String deviceNo;

    private String time;

    private String sign;

    private JSONObject data;

    /**
     * 转换Json且签名
     *
     * @return
     */
    public String toMsg() {
        sign();
        return JSONUtil.toJsonStr(this)+delimiterCode;
    }

  /**
     * 心跳不需要签名
     *
     * @return
     */
    public String toHeartMsg() {
        return JSONUtil.toJsonStr(this)+delimiterCode;
    }


    /**
     * 生成签名
     */
    public void sign() {
        this.time = System.currentTimeMillis() / 1000L + "";
        this.sign = DigestUtil.sha256Hex(this.deviceNo + DigestUtil.sha256Hex(this.time));
    }

    /**
     * 签名验证
     *
     * @return
     */
    public boolean verify() {
        if (StringUtils.isEmpty(this.deviceNo) || this.time == null) {
            return false;
        }

        String cSign = DigestUtil.sha256Hex(this.deviceNo + DigestUtil.sha256Hex(this.time));
        if (StringUtils.isNotEmpty(this.sign) && this.sign.equals(cSign)) {
            return true;
        }
        return false;
    }


    /**
     * 对象转换
     *
     * @param msg
     * @return
     */
    public static MessageObject toMessage(String msg) {
        MessageObject bean = JSONUtil.toBean(msg, MessageObject.class);
        return bean;
    }



}
